package com.zzhua.config;

import com.zzhua.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.Collections;

public class MyRealm extends AuthorizingRealm {

    /**
     * 获取授权信息
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        if ("zhangsan".equals(user.getName())) {
            authInfo.addStringPermission("get:a");
        }
        if ("lisi".equals(user.getName())) {
            authInfo.addStringPermission("get:b");
        }
        if ("wangwu".equals(user.getName())) {
            authInfo.addStringPermission("get:a");
            authInfo.addStringPermission("get:b");
            authInfo.addRoles(Collections.singletonList("role:admin"));
        }
        return authInfo;
    }

    /**
     * 获取认证信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        System.out.println("登录名:" + upToken.getUsername());
        System.out.println("密码:" + Arrays.toString(upToken.getPassword()));

        if ("zhangsan".equals(upToken.getUsername())) {
            return new SimpleAuthenticationInfo(new User("zhangsan", 23), "123456", this.getName());
        } else if ("lisi".equals(upToken.getUsername())) {
            return new SimpleAuthenticationInfo(new User("lisi", 23), "123456", this.getName());
        } else if ("wangwu".equals(upToken.getUsername())) {
            return new SimpleAuthenticationInfo(new User("wangwu", 23), "123456", this.getName());
        }

        return null;
    }
}
